package com.orange.core.security.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.core.security.token.AdminAuthenticationToken;
import com.orange.core.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class AminAuthenticationFilter extends AbstractAuthenticationFilter {

    private final ObjectMapper objectMapper;

    public AminAuthenticationFilter(ObjectMapper objectMapper, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) {
        super(Constants.ADMIN_SIGN_IN_PATH, successHandler, failureHandler);
        this.objectMapper = objectMapper;
    }

    @Override
    protected Authentication obtainToken(HttpServletRequest request) {
        try {
            AdminAuthenticationToken token = objectMapper.readValue(request.getInputStream(), AdminAuthenticationToken.class);
            if (StrUtil.isBlank(token.getName()) || token.getCredentials() == null) {
                throw new InsufficientAuthenticationException("请输入账号和密码");
            }
            return new AdminAuthenticationToken(token.getName().trim(), token.getCredentials().toString().trim(), token.getRememberMe());
        } catch (IOException e) {
            log.error("获取账号密码失败", e);
            throw new InsufficientAuthenticationException("请输入账号和密码");
        }
    }
}
